package com.dzt.btserial;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import com.adayo.btsppsdk.BluetoothCommunication;
import com.adayo.btsppsdk.BtReceiver;
import com.adayo.btsppsdk.constant.HudConnectStatus;
import com.adayo.btsppsdk.listener.OnBTStatusListener;
import com.adayo.btsppsdk.listener.OnSppListener;
import com.adayo.btsppsdk.utils.BluetoothKit;

import java.util.List;

/**
 * Created by dzt on 2017/8/5
 */

public class BtSppPresenter implements Contract.Presenter,
		BtReceiver.OnBtReceiverListener,
		OnSppListener,
		OnBTStatusListener{
	private Contract.View view;
	private BluetoothKit btKit;
	private BluetoothCommunication btCommunication;

	public BtSppPresenter(Contract.View view) {
		this.view = view;
		btKit = BluetoothKit.getInstance();
		btKit.registerBtReceiver();
		btKit.setOnBtReceiverListener(this);
		btCommunication = BluetoothCommunication.getInstance();
		btCommunication.setOnBTStatusListener(this);
		btCommunication.setOnSppListener(this);
	}

	@Override
	public void onConnect(BluetoothDevice device) {
		btCommunication.connectDevice(device);
	}

	@Override
	public void onDisconnect() {
		btCommunication.disconnect();
	}

	@Override
	public boolean isDiscovering() {
		return btKit.isDiscovering();
	}

	@Override
	public void onStartDiscovery() {
		btKit.startDiscovery();
	}

	@Override
	public void onCancelDiscovery() {
		btKit.cancelDiscovery();
	}

	@Override
	public void onPairDevice(BluetoothDevice device) {
		btKit.pairDevice(device);
	}

	@Override
	public BluetoothAdapter getBluetoothAdapter() {
		return btKit.getBluetoothAdapter();
	}

	@Override
	public void onDestroy(){
		btKit.unregisterBtReceiver();
		onDisconnect();
	}

	@Override
	public void onDataReceived(byte[] buffer, int size) {

	}

	@Override
	public void onFoundNewDevice(BluetoothDevice device) {
		view.onFoundNewDevice(device);
	}

	@Override
	public void onSearchFinish(List<BluetoothDevice> list) {
		view.onSearchFinish();
	}

	@Override
	public void onBondStateChange(BluetoothDevice device) {
		if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
			btCommunication.connectDevice(device);
			view.onBonded(device);
		}
	}

	@Override
	public void onSwitchStateChange(int state) {
		view.onSwitchStateChange(state);
	}

	@Override
	public void onSppDisconnected() {
		view.onSppDisconnected();
	}

	@Override
	public void onBTStatusChange(HudConnectStatus status) {
		view.onBTStatusChange(status);
	}
}
